package com.westar.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.westar.base.exceptions.SelfHttpException;
import com.westar.core.conf.SysConst;
import org.apache.commons.codec.Charsets;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import static com.westar.base.enums.HTTPResultEnum.*;

/**
 * 数据对接Cookie保存
 */
public class WestarHttpUtil {

    private static Logger logger = LoggerFactory.getLogger( WestarHttpUtil.class);

    private static CloseableHttpClient httpClient = null;
    /**
     *
     * @param url url地址
     * @param actCookie 唯一标识
     * @param searchParam 参数
     * @return 响应的全部信息
     * @throws IOException
     */
    public static String postMethod(String url,String actCookie, Map<String, String> searchParam) throws IOException {
        Map<String,String> result =  postMethodForAll(url,actCookie, searchParam);
        return  result.get(RESPONEBODY.toString());
    }

    public static Map<String,String> postMethodForAll(String url,String actCookie, Map<String, String> searchParam) throws IOException {

        Map<String, String> headerParam = new HashMap<>();
        headerParam.put("Cookie", actCookie);
        return postMethodForAll(url, searchParam,headerParam);
    }


    public static Map<String,String> postMethodForAll(String url, Map<String, String> searchParam,Map<String, String> headerParam) throws IOException {

        HttpClient httpclientV2 = new HttpClient();
        PostMethod methodV2 = new PostMethod();

        methodV2.setPath(url);
        if(null!= searchParam && !searchParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = searchParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                if(StringUtils.isNotEmpty(key ) && null != value){
                    methodV2.setParameter( key,value);
                }
            }
            methodV2.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        }

        if(null!= headerParam && !headerParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = headerParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                methodV2.addRequestHeader(new Header(key, value));
            }
        }

        int code = httpclientV2.executeMethod(methodV2);

        String responeBody =  methodV2.getResponseBodyAsString();

        Map<String,String> result = new HashMap<>();
        result.put(RESPONEBODY.toString(),responeBody);
        result.put(CODE.toString(),code+"");
        Header[] headers = methodV2.getResponseHeaders();
        if(null != headers){
            for (Header header:headers ) {
                String name = header.getName();
                String value = header.getValue();
                if(name.equalsIgnoreCase("set-cookie")){
                    result.put(COOKIE.toString(),value);
                }else if(name.equalsIgnoreCase("location")){
                    result.put(LOCATION.toString(),value);
                }

            }
        }

        //释放连接
        methodV2.releaseConnection();

        return result;
    }

    public static Map<String,String>  httpPostWithJSON(String url,String actCookie, Map<String, Object> searchParam) throws IOException {

        Map<String, String> headerParam = new HashMap<>();
        headerParam.put("Cookie", actCookie);
        return httpPostWithJSON(url, searchParam,headerParam);
    }

    public static CloseableHttpClient getHttpClient() {
        if (httpClient == null) {
            HttpClientBuilder httpClientBuilder = HttpClients.custom();
            httpClientBuilder.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36");
            httpClient = httpClientBuilder.build();
        }
        return httpClient;
    }

    public static Map<String,String>  httpPostWithJSON(String url,Map<String, Object> searchParam,Map<String, String> headerParam) throws IOException {

        headerParam.put("Content-Type", "application/json;charset=UTF-8");

        CloseableHttpClient closeableHttpClient = getHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String data= JSON.toJSONString(searchParam);
        StringEntity entity = new StringEntity(data, "utf-8");
        entity.setContentEncoding("UTF-8");

        if(null!= headerParam && !headerParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = headerParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                httpPost.setHeader(key, value);
            }
        }
        httpPost.setEntity(entity);

        HttpResponse res = closeableHttpClient.execute(httpPost);

        Map<String,String> result = new HashMap<>();

        result.put(CODE.toString(),res.getStatusLine().getStatusCode()+"");

        if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            result.put(RESPONEBODY.toString(), EntityUtils.toString(res.getEntity(), Charsets.UTF_8));
            org.apache.http.Header[] headers = res.getAllHeaders();
            if(null != headers){
                for (org.apache.http.Header header:headers ) {
                    String name = header.getName();
                    String value = header.getValue();
                    if(name.equalsIgnoreCase("set-cookie")){
                        result.put(COOKIE.toString(),value);
                    }else if(name.equalsIgnoreCase("location")){
                        result.put(LOCATION.toString(),value);
                    }

                }
            }
        }
        httpPost.releaseConnection();
        return result;
    }

    public static Map<String,String> postMethodForAllAndFull(String url,String actCookie, Map<String, String> searchParam) throws IOException {
        Map<String, String> headerParam = new HashMap<>();
        headerParam.put("Cookie", actCookie);
        return postMethodForAllAndFull(url,searchParam,headerParam);
    }

    public static Map<String,String> postMethodForAllAndFull(String url, Map<String, String> searchParam,Map<String, String> headerParam) throws IOException {

        HttpClient httpclientV2 = new HttpClient();
        PostMethod methodV2 = new PostMethod();

        methodV2.setPath(url);
        if(null!= searchParam && !searchParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = searchParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                if(null != value){
                    methodV2.setParameter( key,value);
                }
            }
            methodV2.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        }

        if(null!= headerParam && !headerParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = headerParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                methodV2.addRequestHeader(new Header(key, value));
            }
        }

        int code = httpclientV2.executeMethod(methodV2);

        String responeBody =  methodV2.getResponseBodyAsString();

        Map<String,String> result = new HashMap<>();
        result.put(RESPONEBODY.toString(),responeBody);
        result.put(CODE.toString(),code+"");
        Header[] headers = methodV2.getResponseHeaders();
        if(null != headers){
            for (Header header:headers ) {
                String name = header.getName();
                String value = header.getValue();
                if(name.equalsIgnoreCase("set-cookie")){
                    result.put(COOKIE.toString(),value);
                }else if(name.equalsIgnoreCase("location")){
                    result.put(LOCATION.toString(),value);
                }

            }
        }

        //释放连接
        methodV2.releaseConnection();

        return result;
    }

    /**
     *
     * @param url url地址
     * @param actCookie 唯一标识
     * @param searchParam 参数
     * @return 响应的全部信息
     * @throws IOException
     */
    public static String postMethodWithFull(String url,String actCookie, Map<String, String> searchParam) throws IOException {
        Map<String,String> result =  WestarHttpUtil.postMethodForAllAndFull(url,actCookie,searchParam);
        return result.get(RESPONEBODY.toString());
    }

    public static String postMethodWithFile(String url,
                                            String actCookie,
                                            Map<String, String> searchParam,
                                            FilePart partFile) throws IOException {
        List<FilePart> partFileList = new ArrayList<FilePart>( );
        partFileList.add(partFile);
        return WestarHttpUtil.postMethodWithFiles(url,actCookie,searchParam,partFileList);
    }

    public static String postMethodWithFiles(String url,
                                             String actCookie,
                                             Map<String, String> searchParam,
                                             List<FilePart> partFileList)
            throws IOException {
        Map<String, String> headerParam = new HashMap<>();
        headerParam.put("Cookie", actCookie);
        return  postMethodWithFiles(url,searchParam,partFileList,headerParam);
    }
    /**
     * 上传附件信息
     * @param url 处理的url
     * @param searchParam 普通参数
     * @param partFileList 附件参数
     * @return
     * @throws IOException
     */
    public static String postMethodWithFiles(String url,
                                             Map<String, String> searchParam,
                                             List<FilePart> partFileList,
                                             Map<String, String> headerParam)
            throws IOException {

        HttpClient httpclientV2 = new HttpClient();
        PostMethod methodV2 = new PostMethod();

        methodV2.setPath(url);

        methodV2.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");


        List<Part> partList = new ArrayList<>( );

        if(null!= searchParam && !searchParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = searchParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                if(StringUtils.isNotEmpty(key ) && null != value){
                    partList.add(new StringPart(key,value, "utf-8"));
                }
            }
        }
        if(null != partFileList && !partFileList.isEmpty()){
            partList.addAll(partFileList);
        }

        //Part数组装需要传第的参数和文件等
        Part[] parts = partList.toArray( new Part[partList.size()] );
        MultipartRequestEntity entity = new MultipartRequestEntity(parts, methodV2.getParams());
        methodV2.setRequestEntity(entity);


        if(null!= headerParam && !headerParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = headerParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                methodV2.addRequestHeader(new Header(key, value));
            }
        }
        httpclientV2.executeMethod(methodV2);

        String responeBody =  methodV2.getResponseBodyAsString();

        //释放连接
        methodV2.releaseConnection();

        return responeBody;
    }

    /**
     * 获取附件信息
     * @param fileParam
     * @return
     */
    public static List<FilePart> connectFileByUrl(Map<String, String> fileParam){
        List<FilePart> partList = new ArrayList<FilePart>( );
        if(null!= fileParam && !fileParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = fileParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String fileName = entry.getKey();
                String fileUrl = entry.getValue();
                if(StringUtils.isNotEmpty(fileName ) && null != fileUrl){
                    URL url = null;
                    try {
                        url = new URL(fileUrl);
                        URLConnection connection = url.openConnection();
                        InputStream is = connection.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int len = 0;
                        byte[] b = new byte[1024];
                        while ((len = is.read(b, 0, b.length)) != -1) {
                            baos.write(b, 0, len);
                        }
                        byte[] buffer =  baos.toByteArray();
                        FilePart  filePart = new FilePart(fileName, new ByteArrayPartSource(fileName, buffer));

                        filePart.setCharSet("utf-8");
                        partList.add(filePart);

                    } catch (MalformedURLException e) {
                        logger.error(fileName+" 不存在；其url为：" +fileUrl   );
                    } catch (IOException e) {
                        logger.error(fileName+" 不存在；其url为：" +fileUrl   );
                    }
                }
            }
        }
        return partList;
    }

    /**
     * 封装get请求
     * @param url 访问地址
     * @param actCookie cookie
     * @param searchParam 查询参数
     * @return
     * @throws IOException
     */
    public static String getMethod(String url,String actCookie,Map<String, String> searchParam)
            throws IOException {
        Map<String,String> result =  getForAllMethod(url,actCookie, searchParam);
        return result.get(RESPONEBODY.toString());
    }
    public static  Map<String,String> getForAllMethod(String url,String actCookie,Map<String, String> searchParam)
            throws IOException {
        Map<String, String> headerParam = new HashMap<>();
        headerParam.put("Cookie", actCookie);
        return getForAllMethod(url,searchParam,headerParam);
    }

    public static  Map<String,String> getForAllMethod(String url,Map<String, String> searchParam,Map<String, String> headerParam)
            throws IOException {
        HttpClient httpclientV2 = new HttpClient();
        GetMethod methodV2 = new GetMethod();

        //设置支持https访问
        Protocol myhttpsV2 = new Protocol("https",
                new MySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttpsV2);

        //创建一个uri对象
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if(null!=searchParam && !searchParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = searchParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                uriBuilder.addParameter( entry.getKey(),entry.getValue() );
            }
        }
        methodV2.setPath(uriBuilder.toString());

        if(null!= headerParam && !headerParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = headerParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                String key = entry.getKey();
                String value = entry.getValue();
                methodV2.addRequestHeader(new Header(key, value));
            }
        }

        int code = httpclientV2.executeMethod(methodV2);

        String responeBody =  methodV2.getResponseBodyAsString();

        Map<String,String> result = new HashMap<>();
        result.put(RESPONEBODY.toString(),responeBody);
        result.put(CODE.toString(),code+"");

        Header[] headers = methodV2.getResponseHeaders();
        if(null != headers){
            for (Header header : headers) {
                String name = header.getName();
                String value = header.getValue();

                if(name.toLowerCase().equals("set-cookie")){
                    String tempValue= result.getOrDefault( COOKIE.toString(),"");
                    if(StringUtils.isEmpty(tempValue)){
                        result.put(COOKIE.toString(),value+";");
                    }else{
                        result.put(COOKIE.toString(),tempValue+value+";");
                    }
                }else if(name.toLowerCase().equals("location")){
                    result.put(LOCATION.toString(),value);
                }
            }
        }


        methodV2.releaseConnection();

        return result;
    }

    /**
     * 获办理任务所需要的信息
     * @param actCookie
     * @param affairCode
     * @return
     */
    public static Map<String, String> constrViewTaskParam(String actCookie, String affairCode,String ownerId) throws IOException, SelfHttpException {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/wftask/queryTasks4Affair";
        Map<String,String> searchParam = new HashMap<>(  );
        searchParam.put("page","1"  );
        searchParam.put("rows","10"  );
        searchParam.put("busiAlias","COMMON-MODEL,SCENE");
        searchParam.put("status","10"  );
        searchParam.put("ownerId",ownerId );
        searchParam.put("affairCode",affairCode);

        Map<String,String> httpResult =  postMethodForAll(url,actCookie, searchParam);
        String code = httpResult.get(CODE.toString());
        if(code.equals("200")){
            String responeBody = httpResult.get(RESPONEBODY.toString());
            JSONObject jsonObject = JSON.parseObject(responeBody);
            Integer total = jsonObject.getInteger( "total" );
            if(total == 1){
                Object data = jsonObject.getJSONArray( "rows" ).get( 0 );
                JSONObject resultJson = JSONObject.parseObject( data.toString() );

                Map<String,String> result = new HashMap<>(  );
                result.put( "taskId",resultJson.getString("idForStr") );
                result.put( "procTaskId",resultJson.getString("procTaskId") );
                result.put( "procInstId",resultJson.getString("procInstId") );
                result.put( "busiId",resultJson.getString("busiId") );
                result.put( "nodeId",resultJson.getString("nodeId") );
                result.put( "busiAlias",resultJson.getString("busiAlias") );
                result.put( "status",resultJson.getString("status") );
                return result;
            }else{
                return null;
            }
        }else {
            String location = httpResult.get(LOCATION.toString());
            if(code.equals("302") && location.indexOf("login")>=0 ){
                logger.error(url+"需要重新登录！");
                throw new SelfHttpException(SelfHttpException.PAGE_RE_LOGIN,"需要重新登录","");
            }
            return null;
        }
    }


    public static Map<String,String> constrViewDoneTaskParam(String actCookie, String affairCode, String ownerId) throws IOException {
        //从页面获取数据信息
        String shareKey = WestarHttpUtil.getShareKey(actCookie);

        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/wfDoRecord/queryTaskDone";
        Map<String,String> searchParam = new HashMap<>(  );
        searchParam.put("page","1"  );
        searchParam.put("rows","10"  );
        searchParam.put("busiAlias","COMMON-MODEL"  );
        searchParam.put("status","10"  );
        searchParam.put("handlerId",ownerId );
        searchParam.put("shareKey",shareKey );
        searchParam.put("busiCode",affairCode);
        String responeBody = WestarHttpUtil.postMethod(url,actCookie,searchParam);

        JSONObject jsonObject = JSON.parseObject(responeBody);
        Integer total = jsonObject.getInteger( "total" );
        if(total == 1){
            Object data = jsonObject.getJSONArray( "rows" ).get( 0 );
            JSONObject resultJson = JSONObject.parseObject( data.toString() );

            Map<String,String> result = new HashMap<>(  );
            result.put( "transactor",resultJson.getString("transactor") );

            String taskId = resultJson.getString("taskId");
            taskId = StringUtils.isBlank(taskId)?"0":taskId;
            result.put( "taskId",taskId );
            //临时使用，替换procInstId数据信息
            result.put( "procTaskId",resultJson.getString("procInstId") );
            result.put( "procInstId",resultJson.getString("procInstId") );

            JSONObject customProps = resultJson.getJSONObject("customProps");
            if(null != customProps){
                String busiId = customProps.getString("busiId");
                result.put( "busiId",busiId );
            }else{

            }



            result.put( "nodeId",resultJson.getString("nodeId") );
            result.put( "busiAlias",resultJson.getString("busiAlias") );
            result.put( "status",resultJson.getString("status") );


            return result;
        }else{
            return new HashMap<>( );
        }
    }

    /**
     * 获取用于查询已办数据的shardKey
     * @param actCookie
     * @return
     */
    public static String getShareKey(String actCookie) {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/wfDoRecord/listDoneTaskpage";
        try {
            String responeBody = WestarHttpUtil.getMethod(url,actCookie,null);
            Document doc = Jsoup.parse(responeBody);
            Elements form = doc.select("#form-data");
            String shardKey = form.select( "#shardKey").attr("value");
            return shardKey;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 获取附件信息
     * @param url
     * @param actCookie
     * @param searchParam
     * @param httpServletResponse
     * @return
     * @throws IOException
     */
    public static void getMethodForFile(String url, String actCookie, Map<String, String> searchParam, HttpServletResponse httpServletResponse)
            throws IOException {

        HttpClient httpclientV2 = new HttpClient();
        GetMethod methodV2 = new GetMethod();
        //创建一个uri对象
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if(null!=searchParam && !searchParam.isEmpty()){
            Iterator<Map.Entry<String,String>> itor = searchParam.entrySet().iterator();
            while (itor.hasNext()){
                Map.Entry<String,String> entry = itor.next();
                uriBuilder.addParameter( entry.getKey(),entry.getValue());
            }
        }
        methodV2.setPath(uriBuilder.toString());
        methodV2.addRequestHeader(new Header("Cookie", actCookie));
        httpclientV2.executeMethod(methodV2);

        byte[] filebytes = methodV2.getResponseBody();

        Header header =  methodV2.getResponseHeader( "Content-disposition" );
        if(null == header || StringUtils.isEmpty(header.getValue())){
            return;
        }

        String fileNameJson = methodV2.getResponseHeader( "Content-disposition" ).getValue().split( ";" )[1];
        String responeFileName = fileNameJson.split( "=" )[1] .trim()
                .replaceAll( "\"" ,"");
        //下载PDF
        httpServletResponse.setHeader("Content-Disposition", "attachment;Filename=" + responeFileName);
        OutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(filebytes);
        outputStream.flush();
        outputStream.close();

        methodV2.releaseConnection();
    }

    /**
     * 查询待办的主键
     * @param actCookie
     * @param affairCode
     * @return
     */
    public static String constrViewTaskId(String actCookie, String affairCode) {
        String taskId = null;
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/wftask/queryTaskTodo";
        try {
            Map<String, String> searchParam = new HashMap<>();
            Integer pageSize = 10;
            searchParam.put("currentPage","1");
            searchParam.put("pageSize",pageSize.toString());
            String responeBody = WestarHttpUtil.postMethod(url,actCookie,searchParam);

            JSONObject res = JSONObject.parseObject(responeBody);
            Integer total = res.getInteger("total");
            if(total > 0){
                JSONArray rows = JSONArray.parseArray( res.getString( "rows" ));
                if(null != rows && !rows.isEmpty()) {
                    for (Object data : rows) {
                        JSONObject areaJson = JSONObject.parseObject(data.toString());
                        String affairCodeRes =areaJson.getJSONObject("customProps").getString("affairCode");
                        String idForStr = areaJson.getString("idForStr");
                        if(affairCode.equals(affairCodeRes)){
                            taskId = idForStr;
                            break;
                        }
                    }
                    if(StringUtils.isNotEmpty(taskId)){
                        return taskId;
                    }
                }

                //总页数
                Integer totalPageNum = total/pageSize;
                if(total % pageSize >0){
                    totalPageNum = totalPageNum + 1;
                }
                //查询剩下的页码信息
                for(int i = 2; i <= totalPageNum; i++){
                    searchParam.put("currentPage",i+"");
                    responeBody = WestarHttpUtil.postMethod(url,actCookie,searchParam);
                    rows = JSONArray.parseArray( res.getString( "rows" ));
                    if(null != rows && !rows.isEmpty()) {
                        for (Object data : rows) {
                            JSONObject areaJson = JSONObject.parseObject(data.toString());
                            String affairCodeRes =areaJson.getJSONObject("customProps").getString("affairCode");
                            String idForStr = areaJson.getString("idForStr");
                            if(affairCode.equals(affairCodeRes)){
                                taskId = idForStr;
                                break;
                            }
                        }
                        if(StringUtils.isNotEmpty(taskId)){
                           break;
                        }
                    }
                    if(StringUtils.isNotEmpty(taskId)){
                        return taskId;
                    }
                }
            }
            return taskId;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return taskId;
    }
}
